"use strict"
var program = require('commander')
var fs = require('fs')
var path = require('path')
var utils = require('./utils.js')
var webapps = require('./webapps.js')
var _ = require('lodash')

let rootDir = path.join(__dirname, '../webapp')
let distDir = path.join(__dirname, '../dist')
 
program
  .version('0.0.1')

program
  .command('pack [id]')
  .description('generate a package from a webapp')
  .action(function(id) {
    utils.tarDir(path.join(rootDir, `/${id}`), path.join(rootDir, `/${id}.tar`))
  })

function makePluginXml(params) {
  var id = params.id || ''
  var version = params.version || '1.0.0'
  var desc = params.desc || ''
  var provider = params.provider || 'Team Founder'
  var name = params.name || ''
  var icon = params.icon || 'icon.png'
  var tag = params.tag || ''
  var category = params.category || 'tool'
  var authCode = params.authCode || ''
  var mimeType = params.mimeType || ''
  var i18n = ''
  if (params.i18n) {
    i18n = JSON.stringify(params.i18n)
  }

  return `<?xml version="1.0" encoding="UTF-8"?>
<plugin
  id="${id}"
  version="${version}"
  name="${desc}"
  provider-name="${provider}">
  <requires>
    <import plugin="webapp.core" version="0.1"/>
  </requires>
  <extension 
    point="webapp.core.site"
    name="${name}" 
    icon="${icon}" 
    tag="${tag}" 
    category="${category}" 
    authCode="${authCode}" 
    mimeType="${mimeType}"
    i18n='${i18n}' />
</plugin>`
}

function makeWebApiConf(id) {
  return `<Route /${id} >
   DocumentRoot www
   Methods set GET
</Route>`
}

program
  .command('make [id]')
  .description('generate a package from a webapp')
  .action(function(id) {
    var txt = ''
    var fileName = ''

    let params = _.find(webapps, {id: id})
    if (!params) {
      console.log(`${id} Not Found`)
      return
    }

    if (!fs.existsSync(rootDir)) {
      fs.mkdirSync(rootDir)
    }

    utils.rmDir(path.join(rootDir, `/${id}`))
    fs.mkdirSync(path.join(rootDir, `/${id}`))
    fs.mkdirSync(path.join(rootDir, `/${id}/resources`))
    fs.mkdirSync(path.join(rootDir, `/${id}/resources/www`))
    fs.mkdirSync(path.join(rootDir, `/${id}/resources/www/${id}`))

    txt = makePluginXml(params)
    fileName = path.join(rootDir, `/${id}/plugin.xml`)
    fs.writeFileSync(fileName, txt)

    txt = makeWebApiConf(id)
    fileName = path.join(rootDir, `/${id}/resources/WebApi.conf`)
    fs.writeFileSync(fileName, txt)

    utils.copyDir(path.join(rootDir, `/${id}/resources/www/${id}`), 
            path.join(distDir, `/${id}`))
  })

program.parse(process.argv)